package cn.keyingbo.nettylearning.message.server;

import cn.keyingbo.nettylearning.message.handler.MessageServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

import java.io.IOException;
import java.net.InetSocketAddress;

/**
 * 服务端
 */
public class MessageServer {
    private int serverPort;
    public MessageServer(int serverPort) {
        this.serverPort = serverPort;
    }

    /**
     * 启动
     * @throws Exception
     */
    public void start () throws Exception{
        EventLoopGroup bossGroup = null;
        EventLoopGroup workGroup = null;

        try {
            bossGroup = new NioEventLoopGroup(1);//处理请求连接等
            workGroup = new NioEventLoopGroup();//处理数据发送、接收等
            ServerBootstrap bs = new ServerBootstrap();
            bs.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                                @Override
                                public void initChannel(SocketChannel ch) throws Exception {
                                    ch.pipeline()
                                            .addLast(new LineBasedFrameDecoder(1024))
                                            .addLast(new StringDecoder())
                                            .addLast(new MessageServerHandler());
                                }
                            }
                     );
            ChannelFuture f = bs.bind(serverPort).sync();
            f.channel().closeFuture().sync();
        } finally {
            //资源释放
            bossGroup.shutdownGracefully().sync();
            workGroup.shutdownGracefully().sync();
        }
    }
    //启动服务端
    public static void main(String[] args) throws Exception {
        MessageServer server = new MessageServer(6666);
        server.start();
    }
}
